package org.example.order.controller;


import cn.hutool.core.io.FileUtil;
import jakarta.servlet.http.HttpServletResponse;
import org.example.order.common.APIResponse;
import org.example.order.common.ResponseCode;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@RestController
@RequestMapping("/files")
public class FileController {
    //System.getProperty("user.dir") 获取当前项目的根路径
    private static final String filePath =System.getProperty("user.dir") + "/files/";
    //文件上传的目录的路径

    @PostMapping("/upload")
    public APIResponse upload(MultipartFile file) { //文件流的形式接收前端发送过来的文件
        String originalFilename = file.getOriginalFilename();
        if (!FileUtil.isDirectory(filePath))   {  //如果目录不存在，需要先创建目录
            FileUtil.mkdir(filePath);  //创建一个files目录
        }
        //提供文件存储的完整路径
        //给文件名加一个唯一的标识 ，防止一个文件里面名字相同
        String fileName = System.currentTimeMillis() + "_" +originalFilename; // 202245312_xxx.png
        String realPath = filePath + fileName;  //完整的文件路径
        try {
            FileUtil.writeBytes(file.getBytes(), realPath);  //把文件写进磁盘
        } catch (IOException e) {
            throw new RuntimeException("文件上传失败");
        }

        //返回一个网络连接
        //http://localhost:9090/files/download/xxx.jpg
        String url = "http://localhost:9090/files/download/" + fileName;

        return new APIResponse(ResponseCode.SUCCESS, "上传成功",url);
    }

    //文件下载
    @GetMapping("/download/{fileName}")
    public void download(@PathVariable String fileName, HttpServletResponse response) {
        try {
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));
            response.setContentType("application/octet-stream");
            OutputStream os= response.getOutputStream();
            String realPath = filePath + fileName;  //完整的文件路径
            //获取到文件的字节数组
            byte[] bytes = FileUtil.readBytes(realPath);
            os.write(bytes);
            os.flush();
            os.close();
        } catch (IOException e) {

            e.printStackTrace();
            throw new RuntimeException("文件下载失败");

        }


    }

}
